package com.qywx.service.impl;

import com.qywx.dao.PhotoDao;
import com.qywx.entity.PhotoEntity;
import com.qywx.service.PhotoService;
import com.qywx.utils.ImageUtil;
import com.qywx.utils.R;
import com.qywx.utils.RestTemplateUtil;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.UriComponentsBuilder;

import javax.persistence.Id;
import java.io.*;
import java.net.URI;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;

/**
 * @ClassName PhotoServiceImpl
 * @Description: TODO
 * @Author wmj
 * @Date 2020/3/16
 * @Version V1.0
 **/
@Service("photoService")
public class PhotoServiceImpl implements PhotoService {

    private final static Logger log = LoggerFactory.getLogger(PhotoServiceImpl.class);

    @Autowired
    PhotoDao photoDao;
    @Autowired
    RestTemplateUtil restTemplateUtil;
    @Autowired
    RestTemplate restTemplate;

    @Override
    public R saveImage(MultipartFile file) {
        //上传图片到微信端
        String token = restTemplateUtil.getaccessToken();
        //String urlPath = "https://qyapi.weixin.qq.com/cgi-bin/media/uploadimg?access_token="+token;
        String urlPath = "https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token=" + token + "&type=image";
        URI uri = UriComponentsBuilder.fromHttpUrl(urlPath)
                .queryParam("access_token", token)
                //.queryParam("type", "image")
                .queryParam("name", "media")
                .build().toUri();
        String  media_id = null;
        try {
            InputStream inputStream1 = file.getInputStream();
            Map map = restTemplate.postForObject(uri, new InputStreamResource(inputStream1), Map.class);
            Integer errcode = (Integer) map.get("errcode");
            if (0 != errcode) {
                String errmsg = (String) map.get("errmsg");
                log.info("===========上传图片到微信失败===========" + errmsg, errmsg);
                return R.error("上传图片到微信失败");
            }
            media_id = (String) map.get("media_id");
        } catch (IOException e) {
            e.printStackTrace();
        }

        int id = 0;
        try {
            FileInputStream inputStream = (FileInputStream) file.getInputStream();
            PhotoEntity photoEntity = new PhotoEntity();
            String filename = file.getOriginalFilename();
            photoEntity.setName(filename);
            byte[] byt = new byte[inputStream.available()];
            inputStream.read(byt);
            photoEntity.setPhoto(byt);
            photoDao.saveImage(photoEntity);
            id = photoEntity.getId();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error();
        }
        R r = new R();
        r.put("data",id);
        r.put("avatarMediaid",media_id);
        return r;
    }

    /*@Override
    public R readImage(int id) {
       // String targetPath = "D:/image/4.jpg";
        InputStream input = null;
        String s = null;
        try {
            PhotoEntity photoEntity = photoDao.readImage(id);
            byte[] photo = photoEntity.getPhoto();
            //input = new ByteArrayInputStream(photo);
            s = new String(Base64.encodeBase64(photo));
            //ImageUtil.readBin2Image(input, targetPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        R r = new R();
        return r;
    }*/

    @Override
    public byte[] redImg(int id) {
        PhotoEntity photoEntity = photoDao.readImage(id);
        byte[] photo = photoEntity.getPhoto();
        return photo;
    }
}
